/**
 * Copyright by ChenLiPeng 2018
 * Date:2018年4月23日上午10:09:03
 */
package com.efast.dmom.mgmt.service.les.impl;

import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.efast.cafe.framework.exception.ServiceException;
import com.efast.cafe.framework.util.SpringWebUtils;
import com.efast.dmom.mgmt.dao.les.TtWhmStockOutboundDao;
import com.efast.dmom.mgmt.dao.les.TwInvSkuLoctlDao;
import com.efast.dmom.mgmt.dao.master.TmBasDeliveryUnitDao;
import com.efast.dmom.mgmt.dao.master.TmBasPartDao;
import com.efast.dmom.mgmt.dao.master.TmBasPullUnitDao;
import com.efast.dmom.mgmt.dao.mes.TeMesOutboundDao;
import com.efast.dmom.mgmt.entity.les.TtWhmStockOutbound;
import com.efast.dmom.mgmt.entity.les.TwInvSkuLoctl;
import com.efast.dmom.mgmt.entity.master.TmBasDeliveryUnit;
import com.efast.dmom.mgmt.entity.master.TmBasPart;
import com.efast.dmom.mgmt.entity.master.TmBasPullUnit;
import com.efast.dmom.mgmt.entity.mes.TeMesOutbound;
import com.efast.dmom.mgmt.service.les.MaterialPullService;
import com.efast.dmom.mgmt.utils.Assist;

/**
 * @描述 4.2.3 物料拉动
 * 
 *     产品在某工位完工后，会将物料消耗，并将消耗的物料信息传给WMS系统
 *     （工位编号、消耗物料的物料号+版本号、消耗数量、工厂编号、车间编号、供应商编号、工单、LOT），相应扣减线边库物料表的数量。
 *     当线边库数量低于设定阈值（当下按安全库存为阈值），则出发物料补货请求(参考补货需求)。
 * 
 * @创建人 ChenLiPeng
 * @创建时间 2018年4月23日上午10:09:03
 * @修改人
 * @修改时间 2018年4月23日上午10:09:03
 * @since JDK 1.8
 */
@Service
public class MaterialPullServiceImpl implements MaterialPullService {

	// 零件拉动关系TM_BAS_PULL_UNIT
	@Autowired
	TmBasPullUnitDao tmBasPullUnitDao;

	// 库存表 TW_INV_SKU_LOC_T_L
	@Autowired
	TwInvSkuLoctlDao twInvSkuLoctlDao;

	// 出库记录表 tt_whm_stock_outbound
	@Autowired
	TtWhmStockOutboundDao ttWhmStockOutboundDao;

	// 扣料中间表：TE_MES_OUTBOUND
	@Autowired
	TeMesOutboundDao teMesOutboundDao;

	// 零件主数据信息 tr_bas_part
	@Autowired
	private TmBasPartDao trBasPartDao;

	// 配送单位基本信息 tm_bas_delivery_unit
	@Autowired
	private TmBasDeliveryUnitDao tmBasDeliveryUnitDao;
	

	/**
	 * 产品在某工位完工后，会将物料消耗，并将消耗的物料信息传给WMS系统（工位编号、消耗物料的物料号+版本号、消耗数量、工厂编号、车间编号、供应商编号、工单、LOT），
	 * 相应扣减线边库物料表的数量。当线边库数量低于设定阈值（当下按安全库存为阈值），则觸物料补货请求(参考补货需求)。
	 */
	@Override
	public boolean deductionMateriel(List<TeMesOutbound> listTeMesOutbound) {
		System.out.println();
		System.err.println("mes传递生产消耗数据，wms开始扣库........");
		System.out.println();
		for (TeMesOutbound teMesOutbound : listTeMesOutbound) {
			
			Integer partQty = teMesOutbound.getPartQty();
			
			// 【1】：扣减库存时，根据零件拉动关系表（TM_BAS_PULL_UNIT）中的关系进行扣减对应库位库存。
//			List<TmBasPullUnit> listTmBasPullUnit = tmBasPullUnitDao
//					.selectTmBasPullUnit(new Assist(Assist.andEq("plant_no", teMesOutbound.getPlantNo()),
//							Assist.andEq("workshop_no", teMesOutbound.getWorkshopNo()),
//							Assist.andEq("part_no_version", teMesOutbound.getPartNoVersion())));
//			if (listTmBasPullUnit.size() == 0) {
//				throw new ServiceException(teMesOutbound.getPartNoVersion() + "找不到对应的零件拉动关系");
//			}
			
			// 【2】：扣库存(TW_INV_SKU_LOC_T_L)
//			List<TwInvSkuLoctl> listTwInvSkuLoctl = twInvSkuLoctlDao
//					.selectTwInvSkuLoctl(new Assist(Assist.andEq("part_no_version", teMesOutbound.getPartNoVersion()),
//							Assist.andEq("tm_bas_storage_id", listTmBasPullUnit.get(0).getLocId()),
//							Assist.andGt("available_qty", 0)));
//			if (listTwInvSkuLoctl.size() == 0) {
//				throw new ServiceException(teMesOutbound.getPartNoVersion() + "没有可扣库存");
//			}
//			if (listTwInvSkuLoctl.get(0).getAvailableQty()<0||listTwInvSkuLoctl.get(0).getCurQty()<=0) {
//				throw new ServiceException("可用数量或库存数量不可小于1");
//			}
//			if (listTwInvSkuLoctl.get(0).getAvailableQty()<listTwInvSkuLoctl.get(0).getCurQty()) {
//				throw new ServiceException("库存数量不可小于可用数量");
//			}
//			if (partQty < listTwInvSkuLoctl.get(0).getCurQty()) {
//				TwInvSkuLoctl twInvSkuLoctl3 = new TwInvSkuLoctl();
//				twInvSkuLoctl3.setTwInvSkuLoctlId(listTwInvSkuLoctl.get(0).getTwInvSkuLoctlId());
//				twInvSkuLoctl3.setCurQty(listTwInvSkuLoctl.get(0).getCurQty() - teMesOutbound.getPartQty());
//				twInvSkuLoctl3.setAvailableQty(listTwInvSkuLoctl.get(0).getAvailableQty() - teMesOutbound.getPartQty());
//				twInvSkuLoctlDao.updateNonEmptyTwInvSkuLoctlById(twInvSkuLoctl3);
//				
//				// 【3】：扣库完成后，需要写入出库记录(tt_whm_stock_outbound)，供后续库存追溯
//				insertNonEmptyTtWhmStockOutbound(listTmBasPullUnit, listTwInvSkuLoctl, teMesOutbound);
//				
//				// 【4】：扣库完成后，需要更新状态
////				TeMesOutbound teMesOutbound2 = new TeMesOutbound();
////				teMesOutbound2.setTeMesOutboundId(teMesOutbound.getTeMesOutboundId());
////				teMesOutbound2.setStatus("1"); // 状态 0:新数据 , 1:成功 , 2:失败
////				teMesOutboundDao.updateNonEmptyTeMesOutboundById(teMesOutbound2);
//			} else {
////				double sumQty = 0;
////				for (TwInvSkuLoctl twInvSkuLoctl : listTwInvSkuLoctl) {
////					sumQty += twInvSkuLoctl.getAvailableQty();
////				}
////				if (partQty > sumQty) {
////					throw new ServiceException(teMesOutbound.getPartNoVersion() + "当前可用库存小于消耗");
////				}
////				for (TwInvSkuLoctl twInvSkuLoctl : listTwInvSkuLoctl) {
////					if (partQty > twInvSkuLoctl.getAvailableQty()) {
////						TwInvSkuLoctl twInvSkuLoctl3 = new TwInvSkuLoctl();
////						twInvSkuLoctl3.setTwInvSkuLoctlId(twInvSkuLoctl.getTwInvSkuLoctlId());
////						twInvSkuLoctl3.setCurQty(0);
////						twInvSkuLoctl3.setAvailableQty(0);
////						twInvSkuLoctlDao.updateNonEmptyTwInvSkuLoctlById(twInvSkuLoctl3);
////						
////						// 【3】：扣库完成后，需要写入出库记录(tt_whm_stock_outbound)，供后续库存追溯
////						insertNonEmptyTtWhmStockOutbound(listTmBasPullUnit, listTwInvSkuLoctl, teMesOutbound);
////						
////						// 【4】：扣库完成后，需要更新状态
////						TeMesOutbound teMesOutbound2 = new TeMesOutbound();
////						teMesOutbound2.setTeMesOutboundId(teMesOutbound.getTeMesOutboundId());
////						teMesOutbound2.setStatus("1"); // 状态 0:新数据 , 1:成功 , 2:失败
////						teMesOutboundDao.updateNonEmptyTeMesOutboundById(teMesOutbound2);
////					} else {
////						TwInvSkuLoctl twInvSkuLoctl3 = new TwInvSkuLoctl();
////						twInvSkuLoctl3.setTwInvSkuLoctlId(twInvSkuLoctl.getTwInvSkuLoctlId());
////						twInvSkuLoctl3.setCurQty(twInvSkuLoctl.getAvailableQty() - partQty);
////						twInvSkuLoctl3.setAvailableQty(twInvSkuLoctl.getAvailableQty() - partQty);
////						twInvSkuLoctlDao.updateNonEmptyTwInvSkuLoctlById(twInvSkuLoctl3);
////						
////						// 【3】：扣库完成后，需要写入出库记录(tt_whm_stock_outbound)，供后续库存追溯
////						insertNonEmptyTtWhmStockOutbound(listTmBasPullUnit, listTwInvSkuLoctl, teMesOutbound);
////						
////						// 【4】：扣库完成后，需要更新状态
////						TeMesOutbound teMesOutbound2 = new TeMesOutbound();
////						teMesOutbound2.setTeMesOutboundId(teMesOutbound.getTeMesOutboundId());
////						teMesOutbound2.setStatus("1"); // 状态 0:新数据 , 1:成功 , 2:失败
////						teMesOutboundDao.updateNonEmptyTeMesOutboundById(teMesOutbound2);
////						break;
////					}
////					partQty = partQty - twInvSkuLoctl.getAvailableQty();
////				}
//			}
		}
		System.err.println("mes传递生产消耗数据，wms开始扣库完成........");
		return true;
	}

	// 扣库完成后，需要写入出库记录(tt_whm_stock_outbound)，供后续库存追溯
	public void insertNonEmptyTtWhmStockOutbound(List<TmBasPullUnit> listTmBasPullUnit,
			List<TwInvSkuLoctl> listTwInvSkuLoctl, TeMesOutbound teMesOutbound) {

		TtWhmStockOutbound ttWhmStockOutbound = new TtWhmStockOutbound();
		ttWhmStockOutbound.setTrBasPartSupplId(listTmBasPullUnit.get(0).getTrBasPartSupplId());// 零件供应商关系ID
		ttWhmStockOutbound.setStockPartLotNo(listTwInvSkuLoctl.get(0).getLotNo()); // 零件批次号
		List<TmBasPart> listTmBasPart = trBasPartDao
				.selectTmBasPart(new Assist(Assist.andEq("part_no_version", teMesOutbound.getPartNoVersion())));
		ttWhmStockOutbound.setTmBasPartId(listTmBasPart.get(0).getTmBasPartId()); // 零件ID
		ttWhmStockOutbound.setOutboundQty(teMesOutbound.getPartQty());// 出库数量
		ttWhmStockOutbound.setOutboundUsername(SpringWebUtils.getRequestUser()); // 入库人
		ttWhmStockOutbound.setOutboundTime(new Date()); // 入库时间
		ttWhmStockOutbound.setWarehouseId(listTmBasPullUnit.get(0).getWarehouseId()); // 仓库id
		ttWhmStockOutbound.setWarehouseNo(listTmBasPullUnit.get(0).getWarehouseNo()); // 仓库编号
		ttWhmStockOutbound.setDlocId(listTmBasPullUnit.get(0).getDlocId()); // 库区
		ttWhmStockOutbound.setDlocNo(listTmBasPullUnit.get(0).getDlocNo()); // 库区编号
		ttWhmStockOutbound.setLocId(listTmBasPullUnit.get(0).getLocId()); // 库位
		ttWhmStockOutbound.setLocNo(listTmBasPullUnit.get(0).getLocNo()); // 库位编号
		ttWhmStockOutbound.setTmBasPlantId(listTmBasPullUnit.get(0).getTmBasPlantId()); // 工厂
		ttWhmStockOutbound.setTmBasWorkshopId(listTmBasPullUnit.get(0).getTmBasWorkshopId());// 车间
		ttWhmStockOutbound.setSheetNo(teMesOutbound.getOrderNo()); // 对应单证编号
		ttWhmStockOutbound.setCommonSheetType("14"); // 对应单证类型
		ttWhmStockOutbound.setCurPackageNum(teMesOutbound.getPartQty() / listTwInvSkuLoctl.get(0).getInboundPackQty());// 当前箱数
		List<TmBasDeliveryUnit> listTmBasDeliveryUnit = tmBasDeliveryUnitDao.selectTmBasDeliveryUnit(
				new Assist(Assist.andEq("delivery_unit_no", listTmBasPullUnit.get(0).getDeliveryUnitNo())));
		ttWhmStockOutbound.setTmBasDeliveryUnitId(listTmBasDeliveryUnit.get(0).getTmBasDeliveryUnitId());// 收货地
		List<TmBasDeliveryUnit> listTmBasDeliveryUnit2 = tmBasDeliveryUnitDao.selectTmBasDeliveryUnit(
				new Assist(Assist.andEq("delivery_unit_no", listTmBasPullUnit.get(0).getDeliveryUnitNo())));
		ttWhmStockOutbound.setDeliveryRec(listTmBasDeliveryUnit2.get(0).getTmBasDeliveryUnitId());// 目的地
		ttWhmStockOutbound.setTmBasSupplId(listTmBasPullUnit.get(0).getTrBasPartSupplId());// 供应商本地标识码
		// ttWhmStockOutbound.setOutBoundGroupId(null); // 入库组号
		// ttWhmStockOutbound.setSheetId(); // 对应单证ID
		// ttWhmStockOutbound.setDlocPackageSysid(listTrBasPartStorage.get(0).getPartPackageId());
		// ttWhmStockOutbound.setInterfaceGroupId();// 接口汇总组号
		// ttWhmStockOutbound.setPoType(); // 拉动单类型
		// ttWhmStockOutbound.setVin(vin); // VIN号 预留字段 目前不用
		// ttWhmStockOutbound.setToOutboundFalg(toOutboundFalg); // 生成出库记录标记(外排序单)
		ttWhmStockOutbound.setFlag(0); // 冲销标记
		ttWhmStockOutbound.setIsTosap("0"); // 是否已上传SAP
		ttWhmStockOutbound.setIsCanTosap("1");// 是否允许上传SAP0不允许1允许
		ttWhmStockOutbound.setBaseUnit("EA");// 基本单位
		ttWhmStockOutbound.setMriStatus("0");// 补货需求状态(0:未组织,1:已组织)
		ttWhmStockOutbound.setMarkStatus(1);
		ttWhmStockOutbound.setCompanyCode(SpringWebUtils.getRequestCompany());
		ttWhmStockOutbound.setCreateTime(new Date());
		ttWhmStockOutbound.setCreateUser(SpringWebUtils.getRequestUser());
		ttWhmStockOutboundDao.insertNonEmptyTtWhmStockOutbound(ttWhmStockOutbound);
	}

}
